#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/resource.h>

#define FILE_MODE   0644

int main(int argc, char const* argv[])
{
    int fdin, fdout;
    char *src, *dst;
    struct stat statbuf;
    struct rusage ru;

    if (argc != 3)
    {
        fprintf(stderr, "usage: %s <from> <to>\n", argv[0]);
        exit(0);
    }

    if ((fdin = open(argv[1], O_RDONLY)) < 0)
    {
        fprintf(stderr, "open %s error\n", argv[1]);
        exit(0);
    }

    if ((fdout = open(argv[2], O_RDWR|O_CREAT|O_TRUNC, FILE_MODE)) < 0)
    {
        fprintf(stderr, "create %s error\n", argv[2]);
        exit(0);
    }

    if (fstat(fdin, &statbuf) < 0)
    {
        perror("fstat error\n");
        exit(0);
    }

    if (lseek(fdout, statbuf.st_size-1, SEEK_SET) == -1)
    {
        perror("lseek error\n");
        exit(0);
    }

    if (write(fdout, "", 1) != 1)
    {
        perror("write error");
        exit(0);
    }
    
    if ((src = mmap(NULL, statbuf.st_size, PROT_READ, 
                MAP_FILE|MAP_SHARED, fdin, 0)) == MAP_FAILED)
    {
        perror("mmap error");
        exit(0);
    }

    if ((dst = mmap(NULL, statbuf.st_size, PROT_READ|PROT_WRITE, 
                MAP_FILE|MAP_SHARED, fdout, 0)) == MAP_FAILED)
    {
        perror("mmap error");
        exit(0);
    }

    memcpy(dst, src, statbuf.st_size);
    
    if (getrusage(RUSAGE_SELF, &ru) < 0)
    {
        perror("getrusage error");
        exit(0);
    }

    printf("user time is %ld.%06ld\n", ru.ru_utime.tv_sec,
        ru.ru_utime.tv_usec);
    printf("sys time is %ld.%06ld\n", ru.ru_stime.tv_sec,
        ru.ru_stime.tv_usec);

    return 0;
}
